package com.sudu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sudu.domain.*;
import com.sudu.service.CationService;
import com.sudu.service.UserService;
import com.sudu.service.VideoService;
import com.sudu.service.likeService;
import com.sudu.tool.FileUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
@Api
public class UserController {
    @Autowired
    private UserService userService ;
    @Autowired
    private FileUtil fileUtil ;
    @Autowired
    private likeService likeService ;
    @Autowired
    private VideoService videoService ;
    @Autowired
    private CationService cationService ;


    @ApiOperation(value = "根据id查询用户")
    @GetMapping("/{id}")
    public Result getByID(
            @ApiParam(name = "id" , value = "用户id" , required = true)
            @PathVariable Integer id) {
        User user  = userService.fineByID(id) ;
        Integer code = user != null ? Code.GET_OK : Code.GET_ERR ;
        String msg = user != null ? "" : "数据查询失败，请重试 ！" ;
        Map map=new HashMap();
        map.put("username",user.getUsername());
        map.put("id",user.getId());
        map.put("cardCase",user.getCardCase()) ;
        map.put("handUrl",user.getHandUrl()) ;
        map.put("sex" , user.getSex()) ;
        map.put("phone" , user.getPhone()) ;
        String  resObj= JSON.toJSONString(map);
        JSONObject res = JSON.parseObject(resObj);
        return  new Result(code , res , msg) ;
       }

    @ApiOperation(value = "根据id修改用户个性签名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id" , value = "用户id" , dataType = "String") ,
            @ApiImplicitParam(name = "cardCase" , value = "用户新签名" , dataType = "String")
    })
    @PutMapping("/1")
    public Result updateCardCase(@RequestBody JSONObject obj) {
        int id = obj.getByte("id") ;
        String cardCase = obj.getString("cardCase") ;
        Integer code = userService.updateCardCase(id, cardCase) ? Code.UPDATE_OK : Code.UPDATE_ERR;
        return new Result(code , cardCase) ;
    }

    @ApiOperation(value = "根据id修改用户昵称")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id" , value = "用户id" , dataType = "String") ,
            @ApiImplicitParam(name = "username" , value = "用户新昵称" , dataType = "String")
    })
    @PutMapping("/2")
    public Result updateUsername(@RequestBody JSONObject obj) {
        int id = obj.getByte("id") ;
        String username = obj.getString("username") ;
        Integer code = userService.updateUsername(id, username) ? Code.UPDATE_OK : Code.UPDATE_ERR;
        return new Result(code , username) ;
    }

    @PostMapping("/hander/{id}")
    public Result uploadFile (
            @RequestParam("image")MultipartFile file ,
            @PathVariable Integer id) throws IOException {
        String imgUrl=null;
        User user = userService.fineByID(id) ;
        String delUrl = user.getHandUrl() ;
        String filePath = "/image" ;
        try {
            if(!delUrl.equals("http://1.116.162.146:8080/image/noface.jpg")) {
                fileUtil.deleteFile(delUrl) ;
            }
            imgUrl = fileUtil.uploadOne(filePath , file) ;
            userService.updateHandUrl(id ,imgUrl) ;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(200 , imgUrl , "上传成功！" ) ;
    }

    @PutMapping("/update/{id}")
    public Result updateUserInfo( @PathVariable int id , @RequestBody JSONObject obj) {
        String username = obj.getString("username") ;
        User user = userService.fineByUsername(username) ;
        if(user != null && user.getId() != id) {
            return new Result(20000, null , "该昵称已被占用 !") ;
        }
        String cardCase = obj.getString("cardCase")  ;
        String sex = obj.getString("sex")  ;
        Integer code = userService.updateUserinfo(username , cardCase ,sex , id ) ? Code.UPDATE_OK : Code.UPDATE_ERR;
        Map map=new HashMap();
        map.put("username",username);
        map.put("cardCase",cardCase) ;
        map.put("sex" , sex) ;
        String  resObj= JSON.toJSONString(map);
        JSONObject res = JSON.parseObject(resObj);
        return new Result(code , res) ;
    }

    @PostMapping("/collection/{uid}")
    public Result changeFavorite(@PathVariable int uid , @RequestBody JSONObject obj) {
        int vid = obj.getInteger("vid") ;
        Favorite favorite = likeService.IfFavorite(uid , vid) ;
        if( favorite != null) {
            if(favorite.getIsDelete() == 1) {
                likeService.changeFavorite(uid,vid ,0) ;
                return new Result(Code.GET_OK , 0) ;
            } else {
                likeService.changeFavorite(uid,vid ,1) ;
                return new Result(Code.GET_OK , 1) ;
            }
        } else {
            Favorite favorite1 = new Favorite() ;
            favorite1.setCreateTime(new Date());
            favorite1.setUid(uid);
            favorite1.setVid(vid);
            likeService.saveFavorite(favorite1) ;
            return new Result(Code.GET_OK , 1) ;
        }

    }

    @PostMapping("/subAttention/{uid}")
    public Result changeAttention(@PathVariable int uid , @RequestBody JSONObject obj) {
        int subId = obj.getInteger("subId") ;
        Attention attention = likeService.IfAttention(uid , subId) ;
        if( attention != null) {
            if(attention.getIsDelete() == 1) {
                likeService.changeAttention(uid,subId ,0) ;
                return new Result(Code.GET_OK , 0) ;
            } else {
                likeService.changeAttention(uid,subId ,1) ;
                return new Result(Code.GET_OK , 1) ;
            }
        } else {
            Attention attention1 = new Attention() ;
            attention1.setCreateTime(new Date());
            attention1.setUid(uid);
            attention1.setLikeId(subId);
            likeService.saveAttention(attention1) ;
            return new Result(Code.GET_OK , 1) ;
        }

    }

    @GetMapping("/selectLikeNum/{uid}")
    public Result selectUidNum(@PathVariable int uid) {
        Map map=new HashMap();
        map.put("attention",likeService.selectUidNum(uid));
        map.put("fans",likeService.selectLikeIdNum(uid));
        String  resObj= JSON.toJSONString(map);
        JSONObject res = JSON.parseObject(resObj);
        return new Result(Code.GET_OK , res) ;
    }

    @PostMapping("/upload/{uid}")
    public Result saveVideo(
            @PathVariable int uid , @RequestParam("img")MultipartFile img ,
            @RequestParam("video")MultipartFile video ,
            @RequestParam("title")String title, @RequestParam("tag")String tag
                            ) {
        String imgUrl=null;
        String videoUrl = null ;
        String imgPath = "/cover" ;
        String videoPath = "/video" ;
        int code = 0;
        try {
            imgUrl = fileUtil.uploadOne(imgPath , img) ;
            videoUrl = fileUtil.uploadOne(videoPath , video) ;
            if(imgUrl != null && videoUrl != null) {
                Video video1 = new Video() ;
                video1.setImg(imgUrl);
                video1.setPath(videoUrl);
                video1.setTitle(title);
                video1.setCreateTime(new Date());
                video1.setCreateBy(uid);
                video1.setTag(Integer.parseInt(tag));
              code = videoService.saveVideo(video1) ? Code.SAVE_OK : Code.SAVE_ERR ;
            }
            
        }catch (Exception e) {
            e.printStackTrace();
        }
        
        return new Result(code) ;
    }

    @PostMapping("/del/{vid}")
    public Result deleteByVid(@PathVariable int vid) {
        int code = videoService.deleteByVid(vid) ? Code.DELETE_OK : Code.DELETE_ERR ;
        return new Result(code) ;
    }

    @GetMapping("/talk/human/{uid}")
    public Result getTidByUid(@PathVariable  int uid) {
        return new Result(Code.GET_OK , cationService.getTidByUid(uid) ) ;
    }

    @GetMapping("/talk/{uid}")
    public Result getCommunications( @PathVariable  int uid, int tid, int page, int pageSize) {
        if (page != 0) {
            page = page * pageSize;
        }
        return new Result(Code.GET_OK , cationService.getCommunications(uid, tid, page, pageSize)) ;
    }

    @PostMapping("/connection/{uid}")
    public Result saveConnection (@PathVariable int uid , @RequestBody JSONObject obj) {
        int tid = obj.getInteger("tid") ;
        int code = 0;
        if (cationService.ifConnection(uid,tid)) {
            Communication communication = new Communication() ;
            communication.setUserId(uid);
            communication.setTalkId(tid);
            communication.setConnection(0);
            communication.setCreateTime(new Date());
             code = cationService.saveCationFirst(communication) ? Code.SAVE_OK : Code.SAVE_ERR ;
        }
        return new Result(code) ;
    }

    @PostMapping("/cation/{uid}")
    public Result saveCation(@PathVariable int uid ,@RequestBody JSONObject obj) {
        Communication communication = new Communication() ;
        communication.setUserId(uid);
        communication.setTalkId(obj.getInteger("tid"));
        communication.setContent(obj.getString("content"));
        communication.setCreateTime(new Date());
        int code = cationService.saveCation(communication) ? Code.SAVE_OK : Code.SAVE_ERR ;
        return new Result(code) ;
    }

}
